<template>
  <el-dialog v-model="dialogVisible" :title="`用户权限管理 - ${currentUser?.username}`" width="50%" @close="handleClose">
    <div v-loading="isLoading">
      <el-divider content-position="left">用户专属权限 (User-Specific)</el-divider>
      <!-- <div v-if="userSpecificPermissions.length > 0" class="permission-group">
        <el-tag v-for="perm in userSpecificPermissions" :key="perm" class="permission-tag">
          {{ perm }}
        </el-tag>
      </div> -->
      <div v-if="userSpecificPermissions.length > 0" class="permission-group">
          <div
            v-for="perm in userSpecificPermissions"
            :key="perm"
            @contextmenu.prevent="showContextMenu($event, perm)"
          >
            <el-tag class="permission-tag" closable @close="handleWithdrawPermission(perm)">
              {{ perm }}
            </el-tag>
          </div>
        </div>
      <el-empty v-else description="该用户无专属权限" :image-size="80"></el-empty>
      <div class="mt-3">
        <el-button v-if="!isAddingPermission" type="success" plain @click="startAddPermission" :icon="Plus">
          添加专属权限
        </el-button>
        <div v-else class="add-permission-form">
          <el-select v-model="selectedPermission" placeholder="请选择要添加的权限" filterable class="permission-select">
            <el-option v-for="perm in availablePermissions" :key="perm" :label="perm" :value="perm" />
          </el-select>
          <el-button type="primary" @click="confirmAddPermission">确认添加</el-button>
          <el-button @click="isAddingPermission = false">取消</el-button>
        </div>
      </div>
      <el-divider content-position="left">角色继承权限 (Role-Inherited)</el-divider>
      <el-button v-if="!showRolePermissions" type="primary" link @click="handleShowRolePermissions">
        点击展开/收起【{{ currentUser?.role }}】的角色权限
      </el-button>

      <div v-if="showRolePermissions" class="permission-group">
        <div v-if="rolePermissions.size > 0">
          <el-tag v-for="perm in rolePermissions" :key="perm" type="info" class="permission-tag">
            {{ perm }}
          </el-tag>
        </div>
        <el-empty v-else description="该角色无任何权限" :image-size="80"></el-empty>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { usePermissionService } from '@/stores/permissionService.js';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
const permissionService = usePermissionService();

// --- 组件内部状态 ---
const dialogVisible = ref(false);
const isLoading = ref(false);
const currentUser = ref(null);
const userSpecificPermissions = ref([]);
const rolePermissions = ref(new Set());
const showRolePermissions = ref(false);
const isAddingPermission = ref(false); // 新增：控制添加表单的显示
const selectedPermission = ref('');   // 新增：绑定下拉框选择的权限
// 新增：计算当前用户可用的、尚未拥有的权限
const availablePermissions = computed(() => {
  const allPerms = permissionService.allPermissions;
  const userPerms = new Set([
    ...userSpecificPermissions.value,
    ...rolePermissions.value
  ]);
  return [...allPerms].filter(perm => !userPerms.has(perm));
});

const handleWithdrawPermission = (permission) => {
  ElMessageBox.confirm(
    `确定要撤回用户【${currentUser.value?.username}】的【${permission}】权限吗?`,
    '撤回确认',
    {
      confirmButtonText: '确定撤回',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      isLoading.value = true;
      await permissionService.deleteUserPermission(currentUser.value.id, permission);
      ElMessage.success("权限已成功撤回！");
      
      // 关键：同步更新UI
      const newPermissions = await permissionService.getUsePermission(currentUser.value.id);
      userSpecificPermissions.value = newPermissions || [];

    } catch (error) {
      ElMessage.error("撤回权限失败: " + error);
    } finally {
      isLoading.value = false;
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// --- 方法 ---
const open = async (userData) => {
  currentUser.value = userData;
  dialogVisible.value = true;
  isLoading.value = true;

  try {
    // 调用接口获取用户专属权限
    const permissions = await permissionService.getUsePermission(userData.id);
    userSpecificPermissions.value = permissions || [];
    // 2. 新增：立即从缓存获取该用户的角色权限
      if (userData.roleId) {
        rolePermissions.value = permissionService.getPermissionsByRoleId(userData.roleId);
      }
  } catch (error) {
    ElMessage.error("获取用户专属权限失败: " + error);
    userSpecificPermissions.value = [];
  } finally {
    isLoading.value = false;
  }
};

const handleShowRolePermissions = () => {
  // if (currentUser.value?.roleId) {
  //   // 从 permissionService 的缓存中直接获取角色权限
  //   rolePermissions.value = permissionService.getPermissionsByRoleId(currentUser.value.roleId);
  // }
  showRolePermissions.value = !showRolePermissions.value;
};
// 新增：开始添加权限的方法
const startAddPermission = () => {
  selectedPermission.value = '';
  isAddingPermission.value = true;
};

// 新增：确认添加权限的方法
const confirmAddPermission = async () => {
  if (!selectedPermission.value) {
    ElMessage.warning("请选择一个权限");
    return;
  }

  try {
    isLoading.value = true;
    await permissionService.addUserPermission(currentUser.value.id, selectedPermission.value);
    ElMessage.success("权限添加成功！");

    // 刷新用户专属权限列表
    const permissions = await permissionService.getUsePermission(currentUser.value.id);
    userSpecificPermissions.value = permissions || [];

    // 重置添加状态
    isAddingPermission.value = false;
    selectedPermission.value = '';

  } catch (error) {
    ElMessage.error("添加权限失败: " + error);
  } finally {
    isLoading.value = false;
  }
};

const handleClose = () => {
  // 关闭弹窗时重置所有状态
  currentUser.value = null;
  userSpecificPermissions.value = [];
  rolePermissions.value = new Set();
  showRolePermissions.value = false;
  isAddingPermission.value = false; // 新增：关闭时重置添加状态
  selectedPermission.value = '';  // 新增：清空选择
};

// 暴露 open 方法给父组件
defineExpose({
  open,
});
</script>

<style scoped>
.permission-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.permission-tag {
  font-size: 14px;
}

.el-divider {
  margin-top: 30px;
}
.add-permission-form {
  display: flex;
  gap: 10px;
  align-items: center;
}
.permission-select {
  flex-grow: 1;
}
.mt-3 {
  margin-top: 1rem;
}
</style>